import React, {useEffect} from 'react';
// react-redux
import { connect } from "react-redux";
import {getRankList} from './store'
import { filterIndex } from "../../api/utils";
import {
    Container,
    SongList,
    List,
    ListItem
} from './style';

import Scroll from "../../baseUI/scroll";

function Rank(props) {

    const {rankList: list} = props;
    const {getRankListDataDispatch} = props;

    let rankList = list ? list.toJS () : [];

    //didMount
    useEffect (() => {
        getRankListDataDispatch();
    }, [getRankListDataDispatch]);

    const enterDetail = name => {
        console.log(name);
    };

    let globalStartIndex = filterIndex (rankList);
    let officialList = rankList.slice (0, globalStartIndex);
    let globalList = rankList.slice (globalStartIndex);

    // 这是渲染榜单列表函数，传入 global 变量来区分不同的布局方式
    const renderRankList = (list, global) => {
        return (
            <List globalRank={global}>
                {
                    list.map ((item,index) => {
                        return (
                            <ListItem key={index} tracks={item.tracks} onClick={() => enterDetail (item.name)}>
                                <div className="img_wrapper">
                                    <img src={item.coverImgUrl} alt=""/>
                                    <div className="decorate"></div>
                                    <span className="update_frequecy">{item.updateFrequency}</span>
                                </div>
                                { renderSongList (item.tracks)  }
                            </ListItem>
                        )
                    })
                }
            </List>
        )
    };

    const renderSongList = (list) => {
        return list.length ? (
            <SongList>
                {
                    list.map ((item, index) => {
                        return <li key={index}>{index+1}. {item.first} - {item.second}</li>
                    })
                }
            </SongList>
        ) : null;
    };

    // 榜单数据未加载出来之前都给隐藏
    let displayStyle = !officialList.length ? {"display":"none"}:  {"display": ""};

    return(
        <Container>
            <Scroll>
                <div>
                    <h1 className='offical' style={displayStyle}>
                        官方榜
                    </h1>
                    { renderRankList (officialList) }
                    <h1 className="global" style={displayStyle}> 全球榜 </h1>
                    { renderRankList (globalList, true) }
                </div>
            </Scroll>
        </Container>
    )
}
const mapStateToProps = (state) => ({
    rankList: state.rank.get('rankList'),
});

const mapDispatchToProps = (dispatch) => {
    return{
        getRankListDataDispatch() {
            dispatch (getRankList ());
        }
    }
}

export default connect (mapStateToProps, mapDispatchToProps)(React.memo (Rank));

